import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { IpUtil } from '../utils/ip.util';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger(LoggerMiddleware.name);

  use(req: Request, res: Response, next: NextFunction): void {
    let reqLog = `IP: ${IpUtil.getRealIP(req)}, Method: ${
      req.method
    }, Full URI: ${req.originalUrl},`;

    //print body
    if (this.isJsonContent(req)) {
      reqLog += ` Body: ${JSON.stringify(req.body)}`;
    }
    this.logger.log(reqLog);

    next();
  }

  //check json string
  private isJsonContent(req: Request): boolean {
    const contentType = req.headers['content-type'];
    return contentType && contentType.includes('application/json');
  }
}
